#include "EEExpTree.h"
#include "EEExpMain.h"

int node::nextNodeID = 0;
std::vector<node*> KDTree::treeNodes = std::vector<node*>();


void node::writeTreeStructure(FILE* pFile)
{
	if(WRITE_ASCII)
	{
		fprintf(pFile, "--------\n");
		
		fprintf(pFile, "Node: "); fprintf(pFile, isLeaf() ? "Leaf\n" : "Internal\n");
		fprintf(pFile, "ID: %i\n", id);
		fprintf(pFile, "Parent: %i\n", (parent) ? parent->id : -1);
		fprintf(pFile, "Left Child: %i\n", (pLeftChild) ? pLeftChild->id : -1);
		fprintf(pFile, "Right Child: %i\n", (pRightChild) ? pRightChild->id : -1);
	}
	else
	{	
		WRITESTRING("N", pFile);
		fwrite(&id, sizeof(int), 1, pFile);
		int parentID = (parent) ? parent->id : -1;
		int leftID = (pLeftChild) ? pLeftChild->id : -1;
		int rightID = (pRightChild) ? pRightChild->id : -1;
		fwrite(&parentID, sizeof(int), 1, pFile);
		fwrite(&leftID, sizeof(int), 1, pFile);
		fwrite(&rightID, sizeof(int), 1, pFile);
	}
}

void node::writeLeafData(FILE* pFile)
{
	if(WRITE_ASCII)
	{
		fprintf(pFile, "--------\n");
		fprintf(pFile, "Node ID: %i\n", id);
		if(triangles)
		{	
			fprintf(pFile, "Triangle Count: %i\n", triangles->size());
			for(unsigned int i = 0; i < triangles->size(); i++)
			{
				(*triangles)[i].write(pFile);
			}
		}
		else
		{
			fprintf(pFile, "No Triangles\n");
		}
	}
	else
	{
		WRITESTRING("NT", pFile);
		fwrite(&id, sizeof(unsigned int), 1, pFile);
		unsigned int triangleCount = (triangles) ? (unsigned int)triangles->size() : 0;
		if(triangleCount > 0)
		{	
			fwrite(&triangleCount, sizeof(unsigned int), 1, pFile);	
			for(unsigned int i = 0; i < triangleCount; i++)
			{
				(*triangles)[i].write(pFile);
			}
		}
		else
		{
			fwrite(&triangleCount, sizeof(unsigned int), 1, pFile);	
		}
	}
}